/**
 * 
 */
package com.user_hosted_storage.server.bl;

import java.rmi.RemoteException;
import java.rmi.ServerException;

import javax.ejb.EJBException;
import javax.persistence.OptimisticLockException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import com.user_hosted_storage.dto.CustomStatus;

/**
 * @author helios
 *
 */
@Provider
public class JerseyExceptionMapper implements ExceptionMapper<EJBException> {

	@Override
	public Response toResponse(EJBException e) {
		
		Exception cause = e.getCausedByException();
		
		if(cause instanceof ServerException){
			RemoteException remoteException = (RemoteException) cause.getCause();
			
			if(remoteException.getCause() instanceof WebApplicationException){
				WebApplicationException webApplicationException = (WebApplicationException) remoteException.getCause();
				return webApplicationException.getResponse();
			}
		}
		
		if(cause instanceof OptimisticLockException) {
			return Response.status(CustomStatus.OPTIMISTIC_LOCK_FAILED).build();
		}
		
		return Response.status(Status.INTERNAL_SERVER_ERROR).build();
	}

}
